# 高级分析和报表视图
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.utils import timezone
import json
import logging

from .models_analytics import (
    ReportTemplate, Dashboard, ReportExecution, 
    DataAnalysisTask, KPIMetric, ReportSubscription
)
from .analytics_engine import analytics_engine
from .models import Asset, MaintenanceRecord

logger = logging.getLogger(__name__)


@login_required
def analytics_dashboard(request):
    """分析仪表板主页"""
    
    # 获取用户的仪表板
    user_dashboards = Dashboard.objects.filter(
        Q(created_by=request.user) | Q(shared_users=request.user) | Q(is_public=True)
    ).distinct()[:6]
    
    # 获取最近的报表
    recent_reports = ReportTemplate.objects.filter(
        Q(created_by=request.user) | Q(shared_users=request.user) | Q(is_public=True)
    ).distinct().order_by('-updated_at')[:8]
    
    # 获取KPI指标
    kpi_metrics = KPIMetric.objects.filter(is_active=True)[:8]
    
    # 获取最近的分析任务
    recent_tasks = DataAnalysisTask.objects.filter(
        created_by=request.user
    ).order_by('-created_at')[:5]
    
    # 快速统计
    quick_stats = {
        'total_assets': Asset.objects.count(),
        'active_assets': Asset.objects.filter(status='in_use').count(),
        'maintenance_this_month': MaintenanceRecord.objects.filter(
            maintenance_date__month=timezone.now().month
        ).count(),
        'reports_count': ReportTemplate.objects.filter(created_by=request.user).count(),
    }
    
    context = {
        'user_dashboards': user_dashboards,
        'recent_reports': recent_reports,
        'kpi_metrics': kpi_metrics,
        'recent_tasks': recent_tasks,
        'quick_stats': quick_stats,
    }
    
    return render(request, 'assets/analytics/dashboard.html', context)


@login_required
def report_list(request):
    """报表列表"""
    
    # 获取筛选参数
    report_type = request.GET.get('type', '')
    search = request.GET.get('search', '')
    
    # 构建查询
    reports = ReportTemplate.objects.filter(
        Q(created_by=request.user) | Q(shared_users=request.user) | Q(is_public=True)
    ).distinct()
    
    if report_type:
        reports = reports.filter(report_type=report_type)
    
    if search:
        reports = reports.filter(
            Q(name__icontains=search) | Q(description__icontains=search)
        )
    
    reports = reports.order_by('-updated_at')
    
    # 分页
    paginator = Paginator(reports, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'report_types': ReportTemplate.REPORT_TYPE_CHOICES,
        'current_filters': {
            'type': report_type,
            'search': search,
        }
    }
    
    return render(request, 'assets/analytics/report_list.html', context)


@login_required
@permission_required('assets.add_reporttemplate', raise_exception=True)
def report_designer(request):
    """报表设计器"""
    
    template_id = request.GET.get('template_id')
    template = None
    
    if template_id:
        try:
            template = ReportTemplate.objects.get(id=template_id)
            # 检查权限
            if not (template.created_by == request.user or 
                   request.user in template.shared_users.all() or 
                   template.is_public):
                messages.error(request, '没有权限编辑此报表')
                return redirect('assets:report_list')
        except ReportTemplate.DoesNotExist:
            messages.error(request, '报表模板不存在')
            return redirect('assets:report_list')
    
    # 获取可用的数据源
    data_sources = [
        {'key': 'asset', 'name': '资产', 'fields': get_model_fields('asset')},
        {'key': 'maintenance', 'name': '维修记录', 'fields': get_model_fields('maintenance')},
        {'key': 'category', 'name': '资产类别', 'fields': get_model_fields('category')},
        {'key': 'department', 'name': '部门', 'fields': get_model_fields('department')},
    ]
    
    context = {
        'template': template,
        'data_sources': json.dumps(data_sources),
        'report_types': ReportTemplate.REPORT_TYPE_CHOICES,
        'chart_types': ReportTemplate.CHART_TYPE_CHOICES,
    }
    
    return render(request, 'assets/analytics/report_designer.html', context)


def get_model_fields(model_name):
    """获取模型字段信息"""
    
    field_mappings = {
        'asset': [
            {'name': 'name', 'type': 'string', 'label': '资产名称'},
            {'name': 'asset_number', 'type': 'string', 'label': '资产编号'},
            {'name': 'status', 'type': 'choice', 'label': '状态'},
            {'name': 'purchase_price', 'type': 'decimal', 'label': '采购价格'},
            {'name': 'current_value', 'type': 'decimal', 'label': '当前价值'},
            {'name': 'purchase_date', 'type': 'date', 'label': '采购日期'},
            {'name': 'created_at', 'type': 'datetime', 'label': '创建时间'},
        ],
        'maintenance': [
            {'name': 'maintenance_type', 'type': 'choice', 'label': '维修类型'},
            {'name': 'cost', 'type': 'decimal', 'label': '维修费用'},
            {'name': 'maintenance_date', 'type': 'date', 'label': '维修日期'},
            {'name': 'status', 'type': 'choice', 'label': '状态'},
            {'name': 'created_at', 'type': 'datetime', 'label': '创建时间'},
        ],
        'category': [
            {'name': 'name', 'type': 'string', 'label': '类别名称'},
            {'name': 'code', 'type': 'string', 'label': '类别代码'},
            {'name': 'created_at', 'type': 'datetime', 'label': '创建时间'},
        ],
        'department': [
            {'name': 'name', 'type': 'string', 'label': '部门名称'},
            {'name': 'code', 'type': 'string', 'label': '部门代码'},
            {'name': 'created_at', 'type': 'datetime', 'label': '创建时间'},
        ],
    }
    
    return field_mappings.get(model_name, [])


@login_required
@permission_required('assets.add_reporttemplate', raise_exception=True)
@require_http_methods(["POST"])
def save_report_template(request):
    """保存报表模板"""
    
    try:
        data = json.loads(request.body)
        
        template_id = data.get('template_id')
        name = data.get('name')
        description = data.get('description', '')
        report_type = data.get('report_type')
        chart_type = data.get('chart_type', '')
        data_source = data.get('data_source')
        query_config = data.get('query_config', {})
        report_config = data.get('report_config', {})
        layout_config = data.get('layout_config', {})
        is_public = data.get('is_public', False)
        
        if not all([name, report_type, data_source]):
            return JsonResponse({
                'success': False,
                'message': '缺少必要参数'
            }, status=400)
        
        if template_id:
            # 更新现有模板
            template = get_object_or_404(ReportTemplate, id=template_id)
            
            # 检查权限
            if template.created_by != request.user:
                return JsonResponse({
                    'success': False,
                    'message': '没有权限编辑此报表'
                }, status=403)
            
            template.name = name
            template.description = description
            template.report_type = report_type
            template.chart_type = chart_type
            template.data_source = data_source
            template.query_config = query_config
            template.report_config = report_config
            template.layout_config = layout_config
            template.is_public = is_public
            template.save()
            
            message = '报表模板更新成功'
        else:
            # 创建新模板
            template = ReportTemplate.objects.create(
                name=name,
                description=description,
                report_type=report_type,
                chart_type=chart_type,
                data_source=data_source,
                query_config=query_config,
                report_config=report_config,
                layout_config=layout_config,
                is_public=is_public,
                created_by=request.user
            )
            
            message = '报表模板创建成功'
        
        return JsonResponse({
            'success': True,
            'message': message,
            'template_id': template.id
        })
        
    except Exception as e:
        logger.error(f"保存报表模板失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'保存失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def execute_report(request, template_id):
    """执行报表"""
    
    try:
        template = get_object_or_404(ReportTemplate, id=template_id)
        
        # 检查权限
        if not (template.created_by == request.user or 
               request.user in template.shared_users.all() or 
               template.is_public):
            return JsonResponse({
                'success': False,
                'message': '没有权限执行此报表'
            }, status=403)
        
        # 获取参数
        data = json.loads(request.body) if request.body else {}
        parameters = data.get('parameters', {})
        
        # 创建执行记录
        execution = ReportExecution.objects.create(
            template=template,
            executed_by=request.user,
            parameters=parameters,
            status='running',
            started_at=timezone.now()
        )
        
        # 执行报表
        result = analytics_engine.execute_report(template, parameters)
        
        if result['success']:
            execution.status = 'completed'
            execution.result_data = result
            execution.completed_at = timezone.now()
        else:
            execution.status = 'failed'
            execution.error_message = result.get('error', '未知错误')
        
        execution.save()
        
        return JsonResponse({
            'success': result['success'],
            'execution_id': execution.id,
            'data': result.get('data'),
            'chart_config': result.get('chart_config'),
            'metadata': result.get('metadata'),
            'error': result.get('error')
        })
        
    except Exception as e:
        logger.error(f"执行报表失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'执行失败: {str(e)}'
        }, status=500)


@login_required
def report_view(request, template_id):
    """查看报表"""
    
    template = get_object_or_404(ReportTemplate, id=template_id)
    
    # 检查权限
    if not (template.created_by == request.user or 
           request.user in template.shared_users.all() or 
           template.is_public):
        messages.error(request, '没有权限查看此报表')
        return redirect('assets:report_list')
    
    # 获取最近的执行记录
    recent_executions = ReportExecution.objects.filter(
        template=template
    ).order_by('-created_at')[:5]
    
    context = {
        'template': template,
        'recent_executions': recent_executions,
    }
    
    return render(request, 'assets/analytics/report_view.html', context)


@login_required
def dashboard_list(request):
    """仪表板列表"""
    
    dashboards = Dashboard.objects.filter(
        Q(created_by=request.user) | Q(shared_users=request.user) | Q(is_public=True)
    ).distinct().order_by('-updated_at')
    
    # 分页
    paginator = Paginator(dashboards, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
    }
    
    return render(request, 'assets/analytics/dashboard_list.html', context)


@login_required
@permission_required('assets.add_dashboard', raise_exception=True)
def dashboard_designer(request):
    """仪表板设计器"""
    
    dashboard_id = request.GET.get('dashboard_id')
    dashboard = None
    
    if dashboard_id:
        try:
            dashboard = Dashboard.objects.get(id=dashboard_id)
            # 检查权限
            if dashboard.created_by != request.user:
                messages.error(request, '没有权限编辑此仪表板')
                return redirect('assets:dashboard_list')
        except Dashboard.DoesNotExist:
            messages.error(request, '仪表板不存在')
            return redirect('assets:dashboard_list')
    
    # 获取可用的报表模板
    available_reports = ReportTemplate.objects.filter(
        Q(created_by=request.user) | Q(shared_users=request.user) | Q(is_public=True)
    ).distinct()
    
    context = {
        'dashboard': dashboard,
        'available_reports': available_reports,
    }
    
    return render(request, 'assets/analytics/dashboard_designer.html', context)


@login_required
def kpi_metrics(request):
    """KPI指标管理"""
    
    metrics = KPIMetric.objects.filter(
        created_by=request.user
    ).order_by('name')
    
    context = {
        'metrics': metrics,
        'metric_types': KPIMetric.METRIC_TYPE_CHOICES,
    }
    
    return render(request, 'assets/analytics/kpi_metrics.html', context)


@login_required
@require_http_methods(["POST"])
def create_kpi_metric(request):
    """创建KPI指标"""
    
    try:
        data = json.loads(request.body)
        
        name = data.get('name')
        description = data.get('description', '')
        metric_type = data.get('metric_type')
        data_source = data.get('data_source')
        calculation_config = data.get('calculation_config', {})
        target_value = data.get('target_value')
        warning_threshold = data.get('warning_threshold')
        critical_threshold = data.get('critical_threshold')
        
        if not all([name, metric_type, data_source]):
            return JsonResponse({
                'success': False,
                'message': '缺少必要参数'
            }, status=400)
        
        metric = KPIMetric.objects.create(
            name=name,
            description=description,
            metric_type=metric_type,
            data_source=data_source,
            calculation_config=calculation_config,
            target_value=target_value,
            warning_threshold=warning_threshold,
            critical_threshold=critical_threshold,
            created_by=request.user
        )
        
        # 立即计算一次值
        try:
            new_value = analytics_engine._calculate_kpi_value(metric)
            metric.current_value = new_value
            metric.last_updated = timezone.now()
            metric.save()
        except Exception as e:
            logger.warning(f"计算KPI初始值失败: {e}")
        
        return JsonResponse({
            'success': True,
            'message': 'KPI指标创建成功',
            'metric_id': metric.id
        })
        
    except Exception as e:
        logger.error(f"创建KPI指标失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'创建失败: {str(e)}'
        }, status=500)


@login_required
def data_analysis_tasks(request):
    """数据分析任务"""
    
    tasks = DataAnalysisTask.objects.filter(
        created_by=request.user
    ).order_by('-created_at')
    
    # 分页
    paginator = Paginator(tasks, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'task_types': DataAnalysisTask.TASK_TYPE_CHOICES,
    }
    
    return render(request, 'assets/analytics/analysis_tasks.html', context)


@login_required
@require_http_methods(["POST"])
def create_analysis_task(request):
    """创建数据分析任务"""
    
    try:
        data = json.loads(request.body)
        
        name = data.get('name')
        task_type = data.get('task_type')
        data_source = data.get('data_source')
        analysis_config = data.get('analysis_config', {})
        
        if not all([name, task_type, data_source]):
            return JsonResponse({
                'success': False,
                'message': '缺少必要参数'
            }, status=400)
        
        task = DataAnalysisTask.objects.create(
            name=name,
            task_type=task_type,
            data_source=data_source,
            analysis_config=analysis_config,
            created_by=request.user
        )
        
        # 异步执行分析任务
        if task_type == 'trend':
            result = analytics_engine.perform_trend_analysis(task)
            
            if result['success']:
                task.status = 'completed'
                task.result_data = result.get('data', {})
                task.insights = result.get('insights', [])
                task.completed_at = timezone.now()
            else:
                task.status = 'failed'
                task.error_message = result.get('error', '分析失败')
            
            task.save()
        
        return JsonResponse({
            'success': True,
            'message': '分析任务创建成功',
            'task_id': task.id
        })
        
    except Exception as e:
        logger.error(f"创建分析任务失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'创建失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def update_kpi_metrics_api(request):
    """更新KPI指标API"""
    
    try:
        result = analytics_engine.update_kpi_metrics()
        
        return JsonResponse({
            'success': True,
            'message': f'成功更新 {result["updated_count"]} 个指标',
            'updated_count': result['updated_count'],
            'failed_count': result['failed_count'],
            'errors': result['errors']
        })
        
    except Exception as e:
        logger.error(f"更新KPI指标失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'更新失败: {str(e)}'
        }, status=500)


@login_required
def get_report_data_preview(request):
    """获取报表数据预览"""
    
    try:
        data_source = request.GET.get('data_source')
        query_config = json.loads(request.GET.get('query_config', '{}'))
        
        if not data_source:
            return JsonResponse({
                'success': False,
                'message': '缺少数据源参数'
            }, status=400)
        
        # 创建临时模板用于预览
        temp_template = ReportTemplate(
            data_source=data_source,
            query_config=query_config,
            report_config={}
        )
        
        # 限制预览数据量
        if 'limit' not in query_config:
            query_config['limit'] = 100
        
        result = analytics_engine.execute_report(temp_template, {})
        
        return JsonResponse({
            'success': result['success'],
            'data': result.get('data'),
            'error': result.get('error')
        })
        
    except Exception as e:
        logger.error(f"获取报表数据预览失败: {e}")
        return JsonResponse({
            'success': False,
            'message': f'预览失败: {str(e)}'
        }, status=500)